package com.thti.mecool.client.activity;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ImageButton;

import com.threeti.mecool.core.domain.model.plan.pojo.Plan;
import com.threeti.mecool.core.domain.model.plan.pojo.PlanJob;
import com.threeti.mecool.core.domain.model.plan.pojo.PlanProject;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.command.send.plan.PlanSend;
import com.thti.mecool.client.model.biz.PlanBizImpl;
import com.thti.mecool.client.model.biz.TaskBizImpl;
import com.thti.mecool.client.model.po.PlanClient;
import com.thti.mecool.client.model.po.Task;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.ListWidget;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

public class DraftPlanTaskActivity extends BaseActivity {
	
	private ArrayList<ArrayList<HashMap<String, String>>> taskList;
	private ArrayList<String> listTag;
	private static String curPlanid;
	private ArrayList<HashMap<String, String>> projects;
	private int curPos;
	private ListWidget lw;
	private ArrayList<String> taskids, projectids;
	private PlanBizImpl planBizImpl;
	private TaskBizImpl taskBizImpl;
	private Button cancel,submit;
	private static Activity activity;
	private ProgressDialogWidget pd;
	private Handler handler;
	@Override
	protected void onResume() {
		super.onResume();
		if (lw != null) {
			taskList.clear();
			listTag.clear();
			getData();
//			lw.listExtra(listTag);
			lw.OtherListRefurbish();
		} 
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		noTitle();
		Cache.add(this);
		setContentView(R.layout.mecool_draft_plan_task);
		init();
		initToolbar();
		lw = new ListWidget(this, taskList, listTag);
		lw.getotherlist().setOnCreateContextMenuListener(this);
		ImageButton mecool_add_task = (ImageButton) findViewById(R.id.mecool_add_task);
		handler=new Handler();
		mecool_add_task.setOnClickListener(onClickListener);
	}
	
	Runnable r=new Runnable() {
		@Override
		public void run() {
			if(getDataFlag(HandlerConstant.AddPlanCommand)){
//				planBizImpl.delete(curPlanid, false);
				if(pd.isShowing())
					pd.dismiss();
				Util.sendToast(DraftPlanTaskActivity.this, "添加计划成功！");
				setResult(1);
				handler.removeCallbacks(r);
				finish();
			}else{
				if(getDataFlag(HandlerConstant.CommandFail)){
					if(pd.isShowing())
						pd.dismiss(getCurrentMesg().getContent());
					handler.removeCallbacks(r);
				}else{
					handler.postDelayed(r, 1000);
				}
			}
		}
	};
	
	private void init(){
		activity=this;
		pd=new ProgressDialogWidget(activity,false);
		planBizImpl=new PlanBizImpl(this);
		taskBizImpl=new TaskBizImpl(this);
		submit=(Button)findViewById(R.id.mecool_draft_plan_task_submit);
		cancel=(Button)findViewById(R.id.mecool_draft_plan_task_cancel);
		submit.setOnClickListener(onClickListener);
		cancel.setOnClickListener(onClickListener);
		taskList = new ArrayList<ArrayList<HashMap<String, String>>>();
		listTag = new ArrayList<String>();
		taskids = new ArrayList<String>();
		projectids = new ArrayList<String>();
		Intent i = getIntent();
		curPlanid = i.getStringExtra("curPlanid");
		getData();
	}
	 
	private void getData() {
		TaskBizImpl taskBizImpl = new TaskBizImpl(this);
		List<Task> tasks = taskBizImpl.findAll(curPlanid);
		System.out.println(tasks.size()+"      task size!!");
		for (Task task : tasks) {
			HashMap<String, String> Task = new HashMap<String, String>();
			projects = new ArrayList<HashMap<String, String>>();
			Task.put("name", task.getTaskName());
			Task.put("time", task.getStartTime() + " - " + task.getEndTime());
			Task.put("addr", task.getStoreName());
			taskids.add(task.getId() + "");
			projectids.add(task.getProjectId());
			listTag.add(task.getProjectName());
			projects.add(Task);
			taskList.add(projects);
		}
	}

	private void initToolbar() {
		Toolbar toolbar = new Toolbar(this);
		toolbar.setimage(Toolbar.left_btn, R.drawable.mecool_go_back);
		toolbar.setToolbarCentreText("编辑计划");
		Toolbar.hideRightButton();
		Toolbar.left_btn.setOnClickListener(onClickListener);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuInfo;
		curPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
		menu.add("删除");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (taskids.size() > 1) {
			delListData();
		} else {
			Builder builder = new Builder(this);
			builder.setMessage("这是本计划最后一项任务，确定删除吗？");
			builder.setPositiveButton("确定", dialogOnClickListener)
					.setNegativeButton("取消", dialogOnClickListener);
			builder.create();
			builder.show();
		}
		return super.onContextItemSelected(item);
	}

	private void delListData() {
		lw.delData(curPos);
		TaskBizImpl taskBizImpl = new TaskBizImpl(this);
		taskBizImpl.delete(taskids.get(curPos));
		projectids.remove(curPos);
		taskids.remove(curPos);
		reloadid();
	}

	private DialogInterface.OnClickListener dialogOnClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case -1:
				delListData();
				dialog.dismiss();
				break;
			default:
				dialog.dismiss();
			}
		}
	};

	private void reloadid() {
		ArrayList<String> TempProjectids = new ArrayList<String>();
		ArrayList<String> TempTaskids = new ArrayList<String>();
		TempProjectids.addAll(projectids);
		TempTaskids.addAll(taskids);
		projectids.clear();
		taskids.clear();
		for (String s : TempProjectids) {
			projectids.add(s);
		}
		for (String s : TempTaskids) {
			taskids.add(s);
		}
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_add_task:
				Intent intent = new Intent(DraftPlanTaskActivity.this,
						AddPlanActivity.class);
				intent.putExtra("ContinueAdd", true);
				intent.putExtra("curPlanId", Integer.parseInt(curPlanid));
				startActivity(intent);
				finish();
				break;
			case R.id.mecool_draft_plan_task_submit:
				isUpLoad(curPlanid);
				pd.show();
				handler.post(r);
				break;
			default:
				finish();
				break;
			}
		}
	};
	public void isUpLoad(String planId) {
		PlanClient planClient = planBizImpl.findByPlanId(0,Integer
				.parseInt(planId),String.valueOf(getCurrentUser().getId()));
		List<Task> taskList = taskBizImpl.findAll(planId);
		ObjectMapper mapper = new ObjectMapper();  
		Plan plan = new Plan();
		plan.setName(planClient.getPlanName());
		System.out.println("planClient.getPlanTime()    :    "+planClient.getPlanTime());
		plan.setPlanDate(TimeUtil.stringToDate(planClient.getPlanTime(),0));
		plan.setUserLoginName(getCurrentUser().getLoginName());
		plan.setStatus(HandlerConstant.PLAN_STATUS_NEW);
		List<PlanProject> planProjects = new ArrayList<PlanProject>();
		if (taskList.size() > 0) {
			for (int i = 0; i < taskList.size(); i++) {
				PlanProject planProject=new PlanProject();
				planProject.setProjectCode(taskList.get(i).getProjectId());
				planProject.setProjectName(taskList.get(i).getProjectName());
				List<PlanJob> planJobs = new ArrayList<PlanJob>();
				PlanJob planJob=new PlanJob();
				planJob.setJobId(Long.parseLong(taskList.get(i).getTaskId().trim()));
				planJob.setStoreCode(taskList.get(i).getStoreId());
				planJob.setStartTime(TimeUtil.stringToDate(taskList.get(i).getStartTime(),1));
				planJob.setEndTime(TimeUtil.stringToDate(taskList.get(i).getEndTime(),1));
				planJobs.add(planJob);
				planProject.setPlanJobs(planJobs);
				planProjects.add(planProject);
			}
		}
		plan.setPlanProjects(planProjects);
		Writer strWriter = new StringWriter();
		try {
			mapper.writeValue(strWriter, plan);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String dataJSON = strWriter.toString();
		PlanSend.addPlan(String.valueOf(planClient.getPlanId()),dataJSON);

	}
}
